package com.chinasoft.user.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.chinasoft.common.Constant;
import com.chinasoft.common.ResultData;
import com.chinasoft.user.domain.User;
import com.chinasoft.user.service.UserService;
import com.chinasoft.utils.JedisPoolUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("users")
public class UserController {

    private Jedis jedis = JedisPoolUtil.getJedis();

    @Resource
    private UserService userService;


    @GetMapping("findAll")
    public List<User> findAll(){
       return userService.findAll();
    }

    @PostMapping("register")
    public ResultData addUser(User user){
        try {
            int i = userService.addUser(user);
                if (i == 1) {
                    return new ResultData(Constant.CODE_ONE,Constant.REGISTER_SUCCESS);
                }else{
                    return new ResultData(Constant.CODE_ZERO,Constant.REGISTER_FAILED);
                }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData(Constant.CODE_ZERO,Constant.REGISTER_FAILED);
        }
    }

    @RequestMapping("login")
    public ResultData login(HttpServletRequest request,HttpServletResponse response,User user,String captcha){

//        System.out.println(request.getCookies());
//        //获取cookie中的jedisKey
//        String value=null;
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if (cookie.getName() == "jedisKey"){
//                value = cookie.getValue();
//            }
//        }
//        System.out.println(value);
//        String realCaptcha = null;
//        if (value != null){
//            realCaptcha = jedis.hget(value, "captcha");
//        }
//        System.out.println("从redis中取出来的验证码是："+realCaptcha);

        try {
            if (true) {
                System.out.println("验证码是正确的");
                //获取主体对象
                Subject subject = SecurityUtils.getSubject();
                //token
                subject.login(new UsernamePasswordToken(user.getAccount(), user.getPassword()));
                //验证通过后将用户数据存储到redis
                long time = new Date().getTime();
                Cookie jedisKey = new Cookie("jedisKey", String.valueOf(time));
                response.addCookie(jedisKey);
                //验证通过后返回角色对应的页面
                if(subject.hasRole("rider")){
                    return new ResultData(Constant.CODE_ONE,"rider.html",String.valueOf(time)) ;
                }else if(subject.hasRole("business")){
                    return new ResultData(Constant.CODE_ONE,"business.html",String.valueOf(time)) ;
                }else if(subject.hasRole("admin")){
                    return new ResultData(Constant.CODE_ONE,"admin.html",String.valueOf(time));
                }else{
                    return new ResultData(Constant.CODE_ONE,"index.html",String.valueOf(time));
                }

            }else{
                throw new RuntimeException("verfyCode error");
            }
        } catch (UnknownAccountException e) {
            e.printStackTrace();

        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();

        }catch (RuntimeException e){
            e.printStackTrace();
            System.out.println("runtimexception");
        }
        return new ResultData(Constant.CODE_ZERO,Constant.LOGIN_FAILED) ;
    }

    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login.html";
    }

    @RequestMapping("getImage")
    public void getImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(250, 100, 4, 20);

        long time = new Date().getTime();
//        Map<String,String> captcha1 = new HashMap<>();
//        captcha1.put("captcha",captcha.getCode());
//        jedis.hset(String.valueOf(time),captcha1);
//        Cookie jedisKey = new Cookie("jedisKey", String.valueOf(time));
//        response.addCookie(jedisKey);
        response.setContentType("image/png");
        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(response.getOutputStream());
    }

}
